package com.ruoyi.livedemo.controller;

import com.ruoyi.livedemo.common.ApiResponse;
import com.ruoyi.livedemo.context.CurrentUserHolder;
import com.ruoyi.livedemo.dto.DiaryDetail;
import com.ruoyi.livedemo.dto.DiaryRequest;
import com.ruoyi.livedemo.dto.PagedResult;
import com.ruoyi.livedemo.entity.DiaryEntry;
import com.ruoyi.livedemo.service.DiaryService;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/diaries")
public class DiaryController {

    private final DiaryService diaryService;

    @GetMapping
    public ApiResponse<PagedResult<DiaryEntry>> list(@RequestParam(defaultValue = "0") int page,
                                                     @RequestParam(defaultValue = "10") int size) {
        Long userId = CurrentUserHolder.getUserId();
        return ApiResponse.ok(diaryService.list(userId, page, size));
    }

    @GetMapping("/{id}")
    public ApiResponse<DiaryDetail> get(@PathVariable Long id) {
        Long userId = CurrentUserHolder.getUserId();
        return ApiResponse.ok(diaryService.get(userId, id));
    }

    @PostMapping
    public ApiResponse<DiaryDetail> create(@Valid @RequestBody DiaryRequest request) {
        Long userId = CurrentUserHolder.getUserId();
        return ApiResponse.ok("日记已保存", diaryService.create(userId, request));
    }

    @PutMapping("/{id}")
    public ApiResponse<DiaryDetail> update(@PathVariable Long id, @Valid @RequestBody DiaryRequest request) {
        Long userId = CurrentUserHolder.getUserId();
        return ApiResponse.ok("日记已更新", diaryService.update(userId, id, request));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        Long userId = CurrentUserHolder.getUserId();
        diaryService.delete(userId, id);
        return ApiResponse.ok("日记已删除", null);
    }
}